package sjtu;

import java.util.Scanner;

public class Sjtu1023 {
	public static void main(String[] args) {
		new Sjtu1023().go();
	}
	
	public void go(){
		Scanner scan = new Scanner(System.in);
		int n,a,b;
		n = scan.nextInt();//n组数据
		int[][] arr,temp;
		while(n-- > 0){
			a = scan.nextInt();//边长
			arr = new int[a][a];
			temp = new int[a][a];
			b = scan.nextInt();//方向 0:水平 1:竖直 2:主对角线
			for(int i = 0;i < a;i ++){
				for (int j = 0; j < a; j++) {
					arr[i][j] = scan.nextInt();
				}
			}
			if(b == 0){
				for(int i = 0;i < a;i ++){
					for (int j = 0; j < a; j++) {
						temp[i][a - j - 1] = arr[i][j];
					}
				}
			}else if(b == 1){
				for(int i = 0;i < a;i ++){
					for (int j = 0; j < a; j++) {
						temp[a - i - 1][j] = arr[i][j];
					}
				}
			}else if(b == 2){
				for(int i = 0;i < a;i ++){
					for (int j = 0; j < a; j++) {
						temp[j][i] = arr[i][j];
					}
				}
			}
			for(int[] ar : temp){
				for(int a1 : ar){
					System.out.print(a1+" ");
				}
				System.out.println();
			}
		}
	}
}
